<template>
  <div class="game">
    <div class="game-board">
      <Board :state="currentState" @click="onSquareClick"></Board>
    </div>
    <div class="game-info">
      <input v-model="inputIndex" />
      <div>{{ status }}</div>
      <ol>
        <li v-for="(item, move) in history" :key="move">
          <button @click="onHistoryClick(move)">
            {{ historyInfo(move) }}
          </button>
        </li>
      </ol>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import Board from "@/components/Board.vue";
import { IGameOver } from "@/model/IGameOver";
import { IGameState } from "@/model/IGameState";
import { IGameOverCheck } from "@/controler/GameOverCheck/IGameOverCheck";
import { TicTacTocCheck } from "@/controler/GameOverCheck/TicTacTocCheck";

@Component({
  components: { Board }
})
export default class Game extends Vue {
  // region Prop
  // endregion
  // region Data
  history: IGameState[] = [
    {
      Squares: new Array<string>(9).fill(""),
      IsNextX: true
    }
  ];
  currentIndex = 0;

  gameOverCheck: IGameOverCheck = new TicTacTocCheck();
  // endregion
  // region computed
  get currentState(): IGameState {
    return this.history[this.currentIndex];
  }

  get inputIndex(): number {
    return this.currentIndex;
  }

  set inputIndex(value: number) {
    this.currentIndex = Number(value);
  }

  get gameOver(): IGameOver {
    return this.gameOverCheck.Check(this.currentState);
  }

  get status(): string {
    let outStr = "";
    console.log(this.gameOver);
    if (this.gameOver.Winner !== "") {
      outStr += "胜利者是：" + this.gameOver.Winner;
    } else if (this.gameOver.IsOver) {
      outStr += "平局！";
    } else {
      outStr += "下一个是：";
      outStr += this.currentState.IsNextX ? "X" : "O";
    }

    return outStr;
  }
  // endregion
  // region watch
  // endregion
  // region method
  onSquareClick(index: number) {
    if (this.gameOver.IsOver) {
      return;
    }

    // 在历史状态点击时,删除后面的记录
    if (this.history.length - 1 != this.currentIndex) {
      this.history = this.history.slice(0, this.currentIndex + 1);
    }

    const isNextX = this.currentState.IsNextX;
    const newSquares = new Array<string>(...this.currentState.Squares);
    let chessPiece: string;

    // 这里用历史记录
    if (isNextX) {
      chessPiece = "X";
    } else {
      chessPiece = "O";
    }

    newSquares[index] = chessPiece;

    // 这里构建一个新的数组并推送到 history 里
    this.history.push({
      Squares: newSquares,
      IsNextX: !isNextX
    });

    this.currentIndex += 1;
  }

  historyInfo(index: number): string {
    return index === 0 ? `回到游戏开始` : `跳转到第 #${index}`;
  }

  onHistoryClick(index: number) {
    this.currentIndex = index;
  }
  // endregion
  // region hook
  // endregion
}
</script>

<style></style>
